package com.swgk.core.recyclerview.decoration;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/12/13
 */
public class RecyclerCustomDecoration extends RecyclerView.ItemDecoration {
    private float left = 0;
    private float right = 0;
    private float top = 0;
    private float bottom = 0;
    private Paint dividerPaint;

    public RecyclerCustomDecoration(float left, float right, float top, float bottom) {
        this.left = left;
        this.right = right;
        this.top = top;
        this.bottom = bottom;
    }

    public RecyclerCustomDecoration(float left, float right, float top, float bottom, int color) {
        this.left = left;
        this.right = right;
        this.top = top;
        this.bottom = bottom;
        dividerPaint = new Paint();
        //设置分割线颜色
        dividerPaint.setColor(color);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.top = (int) top;
        outRect.left = (int) left;
        outRect.right = (int) right;
        outRect.bottom = (int) bottom;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (dividerPaint != null) {
            //得到列表所有的条目
            int childCount = parent.getChildCount();
            //得到条目的宽和高
            int left = (int) this.left;
            int right = (int) (parent.getWidth() - this.right);

            for (int i = 0; i < childCount - 1; i++) {
                View view = parent.getChildAt(i);
                //计算每一个条目的顶点和底部 float值
                float top = view.getBottom();
                float bottom = view.getBottom() + this.bottom;
                //重新绘制
                c.drawRect(left, top, right, bottom, dividerPaint);
            }
        }
    }
}
